import { ref, reactive, onMounted, } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { useRoute } from "vue-router";
import qs from "qs";
import { ElMessage } from "element-plus";
import { emitter } from "@/utils/mitt";
import Sortable from 'sortablejs'
import { vLoading } from "element-plus";
import {
  GetInfoByAcrmId,
  FinancingApprovalQuotaGetAllByPagedAndSort,
  AlgorithmSaveResultGetAllNamesOptions,
  AlgorithmicCreditEvaluationModelAlgorithmAnalysis,
  EvaluationAlgorithmResultGetInfo
} from "@/api/stu/SupplyChainFinance";
export function useFincialCredit() {
  const dataList = ref();
  const route = useRoute()
  const loading = ref<boolean>(false);
  const tLoding = ref<boolean>(false)
  const selectData = ref() //选中当前行的数据
  const algorOptionist = ref([]) //算法选择的数据
  const saveParams = ref() //测算的参数
  const detailData = ref('')//算法详情数据
  const listComeData = ref('')//保存后查看
  const showType = ref()
  const dialogVisible = ref(false)
  const selectAcrmId = ref('')
  const formData = reactive({
    supName: '',
    acrmId: '',
    selectParams: '',
    modelName: ''
  })
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "企业名称",
      prop: "supplyName",
    },
    {
      label: "采购项目",
      prop: "projectAccountsReceivableName",
    },
    {
      label: "信用评级模型",
      prop: "modelName",
    },
    {
      label: "信用级别",
      prop: "creditRating",
    },
    {
      label: "融资利率",
      prop: "financingRate",
    },
    {
      label: "审核结果",
      prop: "status",
      fixed: "right",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.creditRating == 'A' || row.creditRating == 'B' ? "success" : "danger"}>
          {
            row.creditRating == '' ? '未审核' : row.creditRating == 'A' || row.creditRating == 'B' ? '已审核通过' : "未审核通过"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const handleCurrentChange = val => {
    getList()
  };
  function handleSizeChange() {
    getList()
  }

  //获取任务列表
  async function getList() {
    const res = await FinancingApprovalQuotaGetAllByPagedAndSort({
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      SEIId: '',
    });
    if (res.success) {
      res.data.items.forEach((item) => {
        item.projectAccountsReceivableName = item.projectAccountsReceivableName.split(";").join(",").replace(/^,/, "");
      })
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }

  //查看模型详情
  async function newGrade(row) {
    selectData.value = row
    formData.supName = row.supplyName
    dialogVisible.value = true
  }

  async function changeAlgro() {
    selectAcrmId.value = formData.acrmId
    formData.modelName = algorOptionist.value.find(item => item.algorithmResultId == formData.acrmId).algorithmModelName
    let data = qs.stringify({
      acrmId: formData.acrmId,
      isCalculate: true
    })
    let res = await GetInfoByAcrmId(data)
    if (res.success) {
      res.data.indexSelection = JSON.parse(res.data.indexSelection)
      res.data.indexSelection.pop()
      saveParams.value = res.data
      formData.selectParams = res.data.indexSelection.map(item => item.Value).join(",");
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function saveCredit() {
    if (!formData.acrmId) {
      ElMessage.warning('请选择评分模型')
      return
    }
    let data = {
      querySqlString: saveParams.value.indexSelection.map(item => item.Key).join(',') + ',creditRating',
      columnName: saveParams.value.indexSelection.map(item => item.Key).join(';') + ';creditRating',
      selectdy: "creditRating",
      algorithmTypeEnum: saveParams.value.type,
      modelType: 1,
      isApprovedMeasurement: true,
      sEIId: selectData.value.seiId,
      updateCreditRating: {
        seiId: "",
        financingApprovalId: selectData.value.financingApprovalId,
        modelName: formData.modelName,
        accountsReceivableAmount: selectData.value.accountsReceivable
      },
      updateQuotaAssessmentModelDto: '',
      algorithmParameters: saveParams.value.type == '2' ? JSON.parse(saveParams.value.modelParameterSetting)
        : '',
      neuralNetworkParameters: saveParams.value.type == '1' ? JSON.parse(saveParams.value.modelParameterSetting) : '',
    }
    let res = await AlgorithmicCreditEvaluationModelAlgorithmAnalysis(data)
    if (res.success) {
      detailData.value = res.data
      dialogVisible.value = false
      tLoding.value = true
      showType.value = saveParams.value.type == '1' ? 'BP神经网络回归' : saveParams.value.type == '2' ? '支持向量机(SVR)回归' : '线性回归'
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  }

  function cancelCreat() {
    // formData.acrmId =
  }

  async function checkPor(row) {
    const data = qs.stringify({
      financingApprovalId: row.financingApprovalId,
      type: 1,
    })
    let res = await EvaluationAlgorithmResultGetInfo(data)
    if (res.success) {
      listComeData.value = JSON.parse(res.data.algorithmCalculateResult)
      showType.value = listComeData.value.type
      tLoding.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }

  onMounted(async () => {
    getList()
    const data = qs.stringify({
      modelType: 1,
      planId: route.query.planId,
      taskId: route.query.taskId
    })
    let res = await AlgorithmSaveResultGetAllNamesOptions(data)
    if (res.success) {
      algorOptionist.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })

  emitter.on("closeNewFincialResult", () => {
    tLoding.value = false
    cancelAlgro()
    listComeData.value = ''
    getList()
  })

  function cancelAlgro() {
    dialogVisible.value = false
    formData.acrmId = ''
    formData.selectParams = ''
  }
  return {
    columns,
    loading,
    dataList,
    pagination,
    dialogVisible,
    tLoding,
    handleSizeChange,
    handleCurrentChange,
    checkPor,
    newGrade,
    detailData,
    formData,
    algorOptionist,
    changeAlgro,
    saveCredit,
    showType,
    saveParams,
    selectData,
    listComeData,
    cancelAlgro,
    selectAcrmId
  }
}